//
//  NSData+TYCodec.m
//  TYFoundation
//
//  Created by 郭艺伟 on 2019/2/28.
//

#import "NSData+TYCodec.h"

@implementation NSData (TYCodec)

+ (NSData *)ty_dataWithBase64EncodedString:(NSString *)string {
    if (![string length]) return nil;
    
    NSData *decoded = nil;
    
    decoded = [[self alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    return [decoded length]? decoded: nil;
}

- (NSString *)ty_base64EncodedString {
    return [self ty_base64EncodedStringWithWrapWidth:0];
}

- (NSString *)ty_base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth {
    if (![self length]) return nil;
    
    NSString *encoded = nil;
    
    switch (wrapWidth) {
        case 64:
        {
            return [self base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        }
        case 76:
        {
            return [self base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
        }
        default:
        {
            encoded = [self base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
        }
    }
    
    if (!wrapWidth || wrapWidth >= [encoded length]) {
        return encoded;
    }
    
    wrapWidth = (wrapWidth / 4) * 4;
    NSMutableString *result = [NSMutableString string];
    for (NSUInteger i = 0; i < [encoded length]; i+= wrapWidth) {
        if (i + wrapWidth >= [encoded length]) {
            [result appendString:[encoded substringFromIndex:i]];
            break;
        }
        [result appendString:[encoded substringWithRange:NSMakeRange(i, wrapWidth)]];
        [result appendString:@"\r\n"];
    }
    
    return result;
}

@end
